package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Override
    public void save(Category category) {
        categoryMapper.save(category);
    }

    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Category> categoryList = categoryMapper.findAll();
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        Page<Category> resPage= new Page<>(pageInfo.getList(),pageInfo.getPageNum(),pageInfo.getPageSize(),pageInfo.getTotal());
        return resPage;
    }

    @Override
    public void delete(long id) {
        int count = dishMapper.findDishWithCategory(id);
        if(count>0){
            throw new CustomException("关联了dish菜单，无法删除");
        }

        int count2 = setmealMapper.findSetMealWithCategory(id);
        if(count2>0){
            throw new CustomException("关联了setmeal菜单，无法删除");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    public List<Category> findByType(Integer type) {
        return categoryMapper.findByType(type);
    }

    @Override
    public Category findById(Long categoryId) {
        return categoryMapper.findById(categoryId);
    }


}
